import React, { useImperativeHandle, useState } from "react";
import Taro from "@tarojs/taro";
import { CoverView, CoverImage } from "@tarojs/components";

import "./index.less";

const TAB_BAR_LIST = [
  {
    id: "home",
    pagePath: "/pages/index/index",
    text: "首页",
    selectedIconPath: "../images/icon-home-active.png",
    iconPath: "../images/icon-home.png",
  },
  {
    id: "publish",
    pagePath: "/pages/publish/index",
    text: "发布",
    iconPath: "../images/icon-middle.png",
    centerItem: true,
  },
  {
    id: "mine",
    pagePath: "/pages/mine/index",
    text: "我的",
    iconPath: "../images/icon-mine.png",
    selectedIconPath: "../images/icon-mine-active.png",
  },
];

const Component = (props, ref) => {
  const [selected, setSelected] = useState(TAB_BAR_LIST[0].id);
  const [show, setShow] = useState(true);
  const switchTab = (item) => {
    setSelected(item.id);
    Taro.switchTab({ url: item.pagePath });
  };
  useImperativeHandle(
    ref,
    () => {
      return {
        setSelected(id) {
          setSelected(id);
        },
        hideTabbar() {
          setShow(false);
        },
      };
    },
    []
  );
  if (!show) return null;
  return (
    <CoverView className="tabbar-container">
      {TAB_BAR_LIST.map((item) => {
        return (
          <CoverView
            key={item.id}
            className={"tabbar-item" + (item.centerItem ? " center-item" : "")}
            onClick={() => {
              switchTab(item);
            }}
          >
            <CoverImage
              className="item-top"
              src={
                selected === item.id && item.selectedIconPath
                  ? item.selectedIconPath
                  : item.iconPath
              }
            />
            {!item.centerItem ? (
              <CoverView
                className={
                  "item-bottom" + (selected == item.id ? " item-active" : "")
                }
              >
                {item.text}
              </CoverView>
            ) : null}
          </CoverView>
        );
      })}
    </CoverView>
  );
};

export default React.forwardRef(Component);
